package com.houger.ddd.filter;

import cn.hutool.core.util.StrUtil;
import com.houger.ddd.service.JwtService;
import com.houger.model.UserLoginInfo;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * 将登录用户的JWT转化成用户信息的全局过滤器
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Resource
    private JwtService jwtService;
    private static final Logger LOGGER = LoggerFactory.getLogger(AuthGlobalFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        final String path = exchange.getRequest().getPath().toString();
        if (StrUtil.isEmpty(token)) {
            // 需要登录的接口，强制校验token，没有则返回403
            if (path.startsWith("/v1/promotion/seckill")){
                return Mono.error(new ResponseStatusException(HttpStatus.FORBIDDEN));
            }
            return chain.filter(exchange);
        }
        //从token中解析用户信息并设置到Header中去
        String realToken = token.replace("Bearer ", "");
        LOGGER.info("AuthGlobalFilter.filter() realToken:{}",realToken);
        final UserLoginInfo userLoginInfo = jwtService.verifyJwt(realToken, UserLoginInfo.class);
        ServerHttpRequest request = exchange.getRequest().mutate()
            .header("userId",userLoginInfo.getUserId().toString()).build();
        exchange = exchange.mutate().request(request).build();
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }


}
